import 'dart:convert';

import 'package:android_intent_plus/android_intent.dart';
import 'package:bruno/bruno.dart';
import 'package:dio/dio.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:sph_driver/http/NoLoadingPostApi.dart';
import 'package:url_launcher/url_launcher.dart';

import '../../AppConfig/Config.dart';
import '../../AppConfig/LocalStorage.dart';
import '../../AppConfig/RouteAct.dart';
import '../../AppConfig/ShowDialog.dart';
import '../../AppConfig/StringEncapsulation.dart';
import '../../Main/Evaluate/EvaluationDetails.dart';
import '../../Message/SingleChatPage.dart';
import '../../http/NoLoadingGetApi.dart';
import '../../http/api.dart';
import '../../l10n/messages.dart';
import 'package:platform/platform.dart';
class ShipperIntroduction extends StatefulWidget {
  const ShipperIntroduction({super.key, required this.shipperId});
  final String shipperId;
  @override
  State<ShipperIntroduction> createState() => _ShipperIntroductionState();
}

class _ShipperIntroductionState extends State<ShipperIntroduction> {
  Map shipperUserMap={};
  List withMeDataList=[];
  List orderDataList=[];
  int checkType =0;
  List allTapList=[];
  List goodTapList=[];
  List midTapList=[];
  List badTapList=[];
  List showList=[];
  int current=1;
  List tagsList=["运费结算准时","运费结算准时","运费结算准时","运费结算准时","运费结算准时","运费结算准时","运费结算准时"];
  @override
  List<String> tagList = [
    '全部',
    '好评',
    '中评',
    '差评',
  ];
  void initState() {
    // TODO: implement initState
    super.initState();
    getDrvUserDetailAction(widget.shipperId);
    allEvaluationAction(1);
    goodEvaluationAction(1);
    midEvaluationAction(1);
    badEvaluationAction(1);
    // postAdd();
  }
  void postAdd()async{
    String? drvId=await UserIdManager.getUserID();
    NoLoadingApiManager.postData(
      context,
      "api/auth/shipper/evaluation/add",
      {
        "waybillId":"12305",
        'driverId':drvId,
        "route":"苏州 吴中区/苏州 吴中区->苏州 吴中区/苏州 吴中区",
        "shipperId":widget.shipperId,
        "level":"POSITIVE",
        "tags":['认证负责',"运费结算准时","尊重司机","装卸货快"],
      },
          (responseData)  {
        setState(() {
        });
      },
    );
  }
  void allEvaluationAction(int current)async{
    String? drvId=await UserIdManager.getUserID();
    NoLoadinggetApiManager.getData(
      context,
      "api/auth/shipper/evaluation/page",
      {'current':current,"size":20,"shipperId":widget.shipperId,"driverId":drvId,"level":""},
          (responseData)  {
        setState(() {
          if(responseData['data']['records'].isNotEmpty){
            allTapList=responseData['data']['records'];
            showList=allTapList;
          }

        });
      },
    );
  }
  void goodEvaluationAction(int current)async{
    String? drvId=await UserIdManager.getUserID();
    NoLoadinggetApiManager.getData(
      context,
      "api/auth/shipper/evaluation/page",
      {'current':current,"size":20,"shipperId":widget.shipperId,"driverId":drvId,"level":"POSITIVE"},
          (responseData)  {
        setState(() {
          if(responseData['data']['records'].isNotEmpty){

            goodTapList=responseData['data']['records'];

          }

        });
      },
    );
  }
  void midEvaluationAction(int current)async{
    String? drvId=await UserIdManager.getUserID();
    NoLoadinggetApiManager.getData(
      context,
      "api/auth/shipper/evaluation/page",
      {'current':current,"size":20,"shipperId":widget.shipperId,"driverId":drvId,"level":"NEUTRAL"},
          (responseData)  {
        setState(() {
          if(responseData['data']['records'].isNotEmpty){

            midTapList=responseData['data']['records'];

          }

        });
      },
    );
  }
  void badEvaluationAction(int current)async{
    String? drvId=await UserIdManager.getUserID();
    NoLoadinggetApiManager.getData(
      context,
      "api/auth/shipper/evaluation/page",
      {'current':current,"size":20,"shipperId":widget.shipperId,"driverId":drvId,"level":"NEGATIVE"},
          (responseData)  {
        setState(() {
          if(responseData['data']['records'].isNotEmpty){

            badTapList=responseData['data']['records'];


          }
        });
      },
    );
  }
  Future<void> getDrvUserDetailAction(String shipperId) async {
    String? drvId=await UserIdManager.getUserID();
    NoLoadinggetApiManager.getData(
      context,
      "api/auth/shipper/user/getBriefUser",
      {'id':shipperId},
          (responseData)  {
        setState(() {
          shipperUserMap=responseData['data'];
        });

      },
    );
  }



  _makePhoneCall(String phoneNumber) async {
    if (LocalPlatform().isAndroid) {
      var status = await Permission.phone.status;
      if (status.isGranted) {
        // 权限已被授予
        // callPhone();
        final AndroidIntent intent = AndroidIntent(
          action: 'android.intent.action.CALL',
          data: Uri.encodeFull('tel:$phoneNumber'),
        );
        await intent.launch();
      } else if (status.isDenied) {
        showCallPhoneFirstDialog(context);
        // 权限被拒绝，但用户可以再次授权
        status = await Permission.phone.request();
        if (status.isGranted) {
          // 用户同意了权限
          // callPhone();
          final AndroidIntent intent = AndroidIntent(
            action: 'android.intent.action.CALL',
            data: Uri.encodeFull('tel:$phoneNumber'),
          );
          await intent.launch();
        } else {
          showCallPhoneDialog(context);
          // 用户拒绝权限，无法发起电话
          // 可以在此处展示信息提示用户需要权限
        }
      } else if (status.isPermanentlyDenied) {
        // 权限被永久拒绝，需要用户手动开启权限
        showCallPhoneDialog(context);
      }

    }else{
      final url =Uri.parse('tel:$phoneNumber');
      if (await canLaunchUrl(url)) {
        await launchUrl(url);
      } else {
        throw '无法拨打电话：$url';
      }
    }
  }
  Future _onRefresh() async {
    if(checkType==0)
      allEvaluationAction(1);
    if(checkType==1)
    goodEvaluationAction(1);
    if(checkType==2)
    midEvaluationAction(1);
    if(checkType==3)
    badEvaluationAction(1);

  }
  Future<void> _loadMoreData() async {
    // 加载更多数据后更新列表
    if (showList.length > 19 * current) {
      current = current + 1;
      if (checkType == 0)
        allEvaluationAction(current);
      if (checkType == 1)
        goodEvaluationAction(current);
      if (checkType == 2)
        if (showList.length > 19) {
          midEvaluationAction(current);
        }
      if (checkType == 3)
        badEvaluationAction(current);
    }
  }
  Widget build(BuildContext context) {
    final screenSize = MediaQuery.of(context).size;
    var messages = AppLocalizations.of(context)!;
    return Scaffold(
      backgroundColor: MyColors.backgreyColor,
      appBar: AppBar(
        centerTitle: true,
        backgroundColor: Colors.white,
        leading: IconButton(
          icon: Icon(Icons.arrow_back_ios, color: Colors.black),
          onPressed: () => Navigator.pop(context,"success"),
        ),
        title: Text("货主简介",style: TextStyle(color: Colors.black,fontSize: 16.sp,fontWeight: FontWeight.w300),),
      ),
      body:
      shipperUserMap.isEmpty?SizedBox(height: 0,):
        Column(
          children: [
            Expanded(child: ListView(
              children: [
                Container(
                  padding: EdgeInsets.only(top: 10.h,bottom: 15.h,left: 15.w,right: 15.w),
                  decoration: BoxDecoration(
                      gradient: LinearGradient(
                        colors: [Color.fromRGBO(246,239,232,1) ,Color.fromRGBO(247,238,234,1) ,Color.fromRGBO(243,238,235,1) ,Color.fromRGBO(239,237,235,1) ,Color.fromRGBO(239,237,235,1) ], // 渐变颜色数组
                        begin: Alignment.topLeft, // 渐变开始的位置
                        end: Alignment.bottomRight, // 渐变结束的位置
                      ),
                      borderRadius: BorderRadius.all(Radius.circular(10))),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Row(
                        // crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Container(
                            width: 60.w,
                            height: 60.h,
                            child:  shipperUserMap['avatarPath']!=null&&shipperUserMap['avatarPath']!=""?
                            CircleAvatar(
                              radius: 15,
                              backgroundImage: NetworkImage(MyServiceUrl.imgHeader +shipperUserMap['avatarPath']),
                            )
                                :
                            CircleAvatar(
                              radius: 15,
                              backgroundImage: AssetImage("lib/Images/login/默认头像.jpeg"),
                            ),
                          ),
                          SizedBox(width: 20.w,),
                          Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Text(shipperUserMap['realName'],style: TextStyle(color: Colors.black,fontSize: 18.sp,fontWeight: FontWeight.w600),),
                              Text(maskPhoneNumber(shipperUserMap['phoneNum']),style: TextStyle(color: Colors.black,fontSize: 14.sp,),),
                            ],
                          ),


                        ],
                      ),
                      SizedBox(height: 15.h,),
                      Container(
                        // height: 10.h,
                        padding: EdgeInsets.only(top: 10.h),
                        decoration: BoxDecoration(
                            color: MyColors.backgreyColor,
                            borderRadius: BorderRadius.all(Radius.circular(10))),
                        child:Column(
                          children: [
                            Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                SizedBox(),
                                Column(
                                  children: [
                                    Text(shipperUserMap['registerDuration']!=null?shipperUserMap['registerDuration']+"天":"--",style: TextStyle(color: Colors.black,fontSize: 16.sp),),
                                    Text("注册时长",style: TextStyle(color: MyColors.textColor,fontSize: 14.sp),),
                                  ],
                                ),
                                Column(
                                  children: [
                                    Text(shipperUserMap['totalNum'].toString(),style: TextStyle(color: Colors.black,fontSize: 16.sp),),
                                    Text("累计交易量",style: TextStyle(color: MyColors.textColor,fontSize: 14.sp),),
                                  ],
                                ),
                                Column(
                                  children: [
                                    Text(shipperUserMap['rating'].toString()+"%",style: TextStyle(color: Colors.black,fontSize: 16.sp),),
                                    Text("好评率",style: TextStyle(color: MyColors.textColor,fontSize: 14.sp),),
                                  ],
                                ),
                                SizedBox(),
                              ],
                            ),
                            SizedBox(height: 10.h,),
                            Container(
                              padding: EdgeInsets.only(left: 15.w,top: 15.h,bottom: 10.h),
                              height: 50.h,
                              decoration: BoxDecoration(
                                gradient: LinearGradient(
                                      colors: [Color.fromRGBO(254,248,241, 1),Colors.white, Colors.white, Colors.white, Colors.white], // 渐变颜色数组
                                      begin: Alignment.topCenter, // 渐变开始的位置
                                      end: Alignment.bottomCenter, // 渐变结束的位置
                                    ),
                                  borderRadius: BorderRadius.all(Radius.circular(10))),
                              child: Row(

                                children: [
                                Text("信用星级",style: TextStyle(color: Colors.black,fontSize: 14.sp,fontWeight: FontWeight.w600),),
                                Row(
                                  children: [
                                    Row(
                                      children: List.generate( (divideAndRound(shipperUserMap['rating'].toString(), 20)), (starIndex) {
                                        return Icon(Icons.star, color: MyColors.themeColor, size: 20.0);
                                      }),
                                    ),
                                    Row(
                                      children: List.generate( (divideAndRound((100-shipperUserMap['rating']).toString(), 20)), (starIndex) {
                                        return Icon(Icons.star_outline, color: MyColors.themeColor, size: 20.0);
                                      }),
                                    ),
                                  ],
                                ),

                              ],),
                            ),
                          ],
                        ),
                      ),
                  ],),
                ),
                Container(
                  color: Colors.white,
                  padding: EdgeInsets.only(left: 15.w,top: 10.h,bottom: 10.h),
                  child:    Text("评价",style: TextStyle(color: Colors.black,fontSize: 16.sp,fontWeight: FontWeight.w600),),
                ),
                  Container(
                  margin: EdgeInsets.only(top: 1.h),
                  padding: EdgeInsets.only(left: 15.w,top: 10.h,bottom: 10.h,right: 15.w),
                  color: Colors.white,
                  child: Column(
                    children: [
                      BrnSelectTag(
                          tags: tagList,
                          spacing: 4.w,
                          tagWidth: 60.w,
                          selectedTagBackgroundColor:Color.fromRGBO(231, 112, 27, 0.85),
                          tagTextStyle:TextStyle(color: Colors.black,fontSize:12.sp ),
                          selectedTagTextStyle:TextStyle(color: MyColors.themeColor,fontSize:12.sp ),
                          initTagState: [true],
                          onSelect: (selectedIndexes) {
                            setState(() {
                              checkType=int.parse(selectedIndexes.toString().replaceAll("[", "").replaceAll("]", ""));
                              if(checkType==0) {
                                current = 1;
                                showList = allTapList;
                              }
                              if(checkType==1) {
                                current = 1;
                                showList = goodTapList;
                              }
                              if(checkType==2) {
                                current = 1;
                                showList = midTapList;
                              }
                              if(checkType==3) {
                                current = 1;
                                showList = badTapList;
                              }
                            });
                          }),
                ]
                  )
                ),
                EasyRefresh(
                  header:
                  ClassicHeader(
                    dragText: '下拉刷新',
                    armedText: '准备释放',
                    readyText: '加载中...',
                    processingText: '加载中...',
                    processedText: '刷新成功',
                    noMoreText: '暂无更多',
                    failedText: '刷新失败',
                    messageText: '刷新时间 %T',
                  ),

                  footer: ClassicFooter(
                    dragText: '加载更多',
                    armedText: '准备释放',
                    readyText: '加载中...',
                    processingText: '加载中...',
                    processedText: '加载成功',
                    noMoreText: '暂无更多',
                    failedText: '加载失败',
                    messageText: '加载时间 %T',
                  ),
                  onRefresh: _onRefresh,
                  onLoad: showList.length>19?_loadMoreData:null,
                  child:
                Container(
                  margin: EdgeInsets.only(top: 1.h),
                  height: screenSize.height-400.h,
                  child:ListView.builder(
    // physics: NeverScrollableScrollPhysics(),
                      itemCount:showList.length,
                      itemBuilder: (BuildContext context, int index) {
                        return GestureDetector(
                          child: Container(
                            color: Colors.white,
                            padding: EdgeInsets.only(top: 15.h,left: 15.w,right: 15.w),
                            child:Column(
                              children: [

                                Row(
                                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                      children: [
                                        Row(
                                          children: [
                                            Container(
                                              width: screenSize.width-100.w,
                                              child:Text(showList[index]['route'],maxLines: 1,style: TextStyle(color: MyColors.textColor,fontSize: 14.sp,fontWeight: FontWeight.w600, overflow:TextOverflow.ellipsis,),),

                                            )
                                          ],
                                        ),

                                        if(checkType==1)
                                        Image.asset("lib/Images/PersonCenter/我的评价好评.png",width: 57.w,height: 20.h,),
                                        if(checkType==2)
                                          Image.asset("lib/Images/PersonCenter/我的评价中评.png",width: 57.w,height: 20.h,),
                                        if(checkType==3)
                                          Image.asset("lib/Images/PersonCenter/我的评价差评.png",width: 57.w,height: 20.h,),
                                        if(checkType==0)
                                          showList[index]['level']=="POSITIVE"? Image.asset("lib/Images/PersonCenter/我的评价好评.png",width: 57.w,height: 20.h,)
                                          :showList[index]['level']=="NEUTRAL"?Image.asset("lib/Images/PersonCenter/我的评价中评.png",width: 57.w,height: 20.h,)
                                          :Image.asset("lib/Images/PersonCenter/我的评价差评.png",width: 57.w,height: 20.h,),

                                      ],
                                    ),
                                    SizedBox(height: 8.h,),
                                    Row(
                                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                      crossAxisAlignment: CrossAxisAlignment.start,
                                      children: [
                                       showList[index]['tags']!=null?
                                        Container(
                                          width: screenSize.width - 200.w,
                                          child: Wrap(
                                            spacing:4.w, // 两个Container之间的水平间距
                                            runSpacing: 4.h, // 行与行之间的垂直间距
                                            children: List<Widget>.from(showList[index]['tags'].map((length) {
                                              return Container(
                                                width: 75.w, // Container宽度
                                                height: 20.h, // Container高度，使其成为正方形
                                                decoration: BoxDecoration(
                                                  border: Border.all(
                                                    color: MyColors.hintColor, // 边框颜色
                                                    width: 0.5, // 边框宽度
                                                  ),
                                                  color: Colors.white, // 根据状态决定颜色
                                                  borderRadius: BorderRadius.circular(3.0), // 设置Container的圆角
                                                ),
                                                child: Center(
                                                  child: Text(
                                                    length,
                                                    maxLines: 1,
                                                    style: TextStyle(
                                                      overflow: TextOverflow.ellipsis,
                                                      fontSize: 10.sp,
                                                      color: MyColors.authTipColor, // 文字颜色为白色
                                                    ),
                                                  ),
                                                ),
                                              );
                                            })),
                                          ),
                                        ):SizedBox(),

                                        Container(
                                          width: 130.w,
                                          child: Text(showList[index]['createTime'].substring(0, 10)+"发表评论",style: TextStyle(color: MyColors.authTipColor,fontSize: 12.sp),),
                                        ),
                                      ],
                                    ),


                                SizedBox(height: 10.h,),
                                Divider(height: 1.h,color: MyColors.backgreyColor,),
                              ],
                            ),

                          ) ,
                          onTap: (){

                          },
                        )
                         ;} ),
                ),
    ),
              ],
            ),
            ),
            // Container(
            //   color: Colors.white,
            //   height: 84.h,
            //   width: screenSize.width,
            //   padding: EdgeInsets.only(top: 10.h,bottom: 40.h),
            //   child: Center(
            //     child: BrnSmallMainButton(
            //       title: '拨打电话',
            //       textColor: Colors.white,
            //       bgColor: MyColors.themeColor,
            //       radius: 30,
            //       width:screenSize.width-40.w,
            //
            //       onTap: () {
            //         _makePhoneCall(shipperUserMap['phoneNum']);
            //       },
            //     ),
            //   ),
            //
            // )
          ],
        ),
    );
  }
}
